//
//  GoodInfoViewController.m
//  BaseFrame
//
//  Created by 孟学浩 on 2017/4/5.
//  Copyright © 2017年 com.mxh. All rights reserved.
//

#import "GoodInfoViewController.h"
#import "CountView.h"
#import "GoodInfoTableViewCell.h"
#import "CooperationTableViewCell.h"
#import "CommunicationTableViewCell.h"
#import "OrderInfoViewController.h"
#import "GoodsInfoModel.h"
#import "GoodsAddOrderModel.h"
#import "AddOrderViewController.h"

@interface GoodInfoViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) UIView *headerView;
@property (nonatomic,strong) UIView *footerView;
@property (nonatomic,strong) UIView *funcView;

@property (nonatomic,strong) SDCycleScrollView *sdcScrollView;
@property (nonatomic,strong) UILabel *titleMoneyLabel;
@property (nonatomic,strong) CountView *countView;

@property (nonatomic,strong) NSDictionary *model;
@property (nonatomic,strong) NSArray *dataArray;
@property (nonatomic,strong) NSDictionary *dataDictionary;
Strong NSMutableArray *imgArray;

- (void)setHeaderInfo;

@end

//网络
@implementation GoodInfoViewController (NetWorking)

- (void)getData{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"c_id":self.gId};
    [[AFAppDotNetAPIClient sharedClient] POST:@"Commodity/selectBycId.action" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"ResponseStatus"] integerValue] == 0) {
            self.model = responseObject[@"selectByCid"];
            NSDictionary *dataDictionary = self.model;
            if (![dataDictionary[@"c_picture_one"] isEqualToString:@" "]) {
                [self.imgArray addObject:dataDictionary[@"c_picture_one"]];
            }
            if (![dataDictionary[@"c_picture_two"] isEqualToString:@" "]) {
                [self.imgArray addObject:dataDictionary[@"c_picture_two"]];
            }
            if (![dataDictionary[@"c_picture_three"] isEqualToString:@" "]) {
                [self.imgArray addObject:dataDictionary[@"c_picture_three"]];
            }
            if (![dataDictionary[@"c_picture_four"] isEqualToString:@" "]) {
                [self.imgArray addObject:dataDictionary[@"c_picture_four"]];
            }
            if (![dataDictionary[@"c_picture_five"] isEqualToString:@" "]) {
                [self.imgArray addObject:dataDictionary[@"c_picture_five"]];
            }
            if (![dataDictionary[@"c_picture_six"]  isEqualToString:@" "]) {
                [self.imgArray addObject:dataDictionary[@"c_picture_six"]];
            }
            if (![dataDictionary[@"c_picture_seven"] isEqualToString:@" "]) {
                [self.imgArray addObject:dataDictionary[@"c_picture_seven"]];
            }
            if (![dataDictionary[@"c_picture_eight"] isEqualToString:@" "]) {
                [self.imgArray addObject:dataDictionary[@"c_picture_eight"]];
            }
            [self.view addSubview:self.tableView];
            [self.view addSubview:self.funcView];
            [self setHeaderInfo];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}

- (void)getAddToCartClick:(NSString *)cId{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"auId":[UserModel sharedInstanced].userId,
                                 @"c_id":cId};
    [[AFAppDotNetAPIClient sharedClient] POST:@"ShoppingCartVo/insertSc.action" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        ShowMessage(responseObject[@"msg"]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}

@end

//UI
@implementation GoodInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"商品详情";

}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
}

#pragma mark - Event

- (void)buyEvent{
    AddOrderViewController *vc = [AddOrderViewController new];
    vc.sId = _model[@"s_id"];
    vc.cId = _model[@"c_id"];
    vc.num = self.count;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)joinBuyCarEvent{
//    if ([[UserModel sharedInstanced].userId isEqualToString:@""]) {
//        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"LoginViewController"]];
//        nav.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
//        [self presentViewController:nav animated:YES completion:nil];
//        return;
//    }
//    
//    if (self.isInBuyCar) {
//        if (self.deleteHandle) {
//            self.deleteHandle();
//        }
//        [self.navigationController popViewControllerAnimated:YES];
//    }else{
    [self getAddToCartClick:_model[@"c_id"]];
        //    }
}

#pragma mark - UITableViewDelegate & UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

            GoodInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([GoodInfoTableViewCell class])];
            cell.imgArray = self.imgArray;
            cell.dataDictionary = self.model;
            return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 27 + 10 + 5 + SCREEN_WIDTH / 4 * self.imgArray.count + + self.imgArray.count * 5;
}

- (void)setHeaderInfo{
    NSString *urlString = [NSURL URLOffsetIPWithString:_model[@"c_first_figure"]].absoluteString;
    _sdcScrollView.imageURLStringsGroup = @[urlString];
    
//    NSString *title = _model.commodityName;
//    NSString *nowPrice = _model.floorPrice;
//    NSString *oldPrice = _model.commodityPrice;
    
    NSString *title = _model[@"c_name"];
    NSString *nowPrice = _model[@"c_unit_price"];
    
    NSString *nowPriceString = [NSString stringWithFormat:@"现价   ¥%@",nowPrice];
    NSString *temp = [NSString stringWithFormat:@"%@\n%@",title,nowPriceString];
    
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:temp];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:5];
    [attStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [temp length])];
    [attStr addAttribute:NSForegroundColorAttributeName value:getColor(redColor) range:[temp rangeOfString:nowPriceString]];
    [attStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15 weight:1] range:[temp rangeOfString:title]];
    
    _titleMoneyLabel.attributedText = attStr;
}

#pragma mark - set & get

- (UITableView *)tableView{
    if (!_tableView) {
        
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-44) style:UITableViewStyleGrouped];
        _tableView.bounces = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.sectionFooterHeight = 5;
        _tableView.sectionHeaderHeight = .01;
        _tableView.tableFooterView = self.footerView;
        _tableView.tableHeaderView = self.headerView;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[GoodInfoTableViewCell class] forCellReuseIdentifier:NSStringFromClass([GoodInfoTableViewCell class])];
//        [_tableView registerClass:[CooperationTableViewCell class] forCellReuseIdentifier:NSStringFromClass([CooperationTableViewCell class])];
//        [_tableView registerClass:[CommunicationTableViewCell class] forCellReuseIdentifier:NSStringFromClass([CommunicationTableViewCell class])];
    }
    return _tableView;
}

- (UIView *)headerView{
    if (!_headerView) {
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 186/WIDTH_5S_SCALE + 70)];
        _headerView.backgroundColor = [UIColor whiteColor];
        _sdcScrollView = [[SDCycleScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 186/WIDTH_5S_SCALE)];
        _sdcScrollView.backgroundColor = getColor(@"f1f2f6");
        
        _titleMoneyLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, CGRectGetMaxY(_sdcScrollView.frame), SCREEN_WIDTH-20, 65)];
        _titleMoneyLabel.font = DEF_FontSize_12;
        _titleMoneyLabel.numberOfLines = 2;
        
        _countView = [[CountView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 105, 0, 90, 30)];
        _countView.center = CGPointMake(_countView.center.x, _titleMoneyLabel.center.y);
        _countView.count = [self.count intValue];
        __block typeof(self) bSelf = self;
        _countView.valueChangeHandle = ^(int count) {
            NSLog(@"%d",count);
            bSelf.count = [NSString stringWithFormat:@"%d",count];
        };
//        UIButton *joinBuyCarBtn = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMinX(_countView.frame), CGRectGetMaxY(_countView.frame)+5, 90, 20)];
//        [joinBuyCarBtn setTitle:self.isInBuyCar?@"移除购物车":@"加入购物车" forState:UIControlStateNormal];
//        [joinBuyCarBtn setTitleColor:getColor(redColor) forState:UIControlStateNormal];
//        joinBuyCarBtn.titleLabel.font = DEF_FontSize_13;
//        [joinBuyCarBtn addTarget:self action:@selector(joinBuyCarEvent) forControlEvents:UIControlEventTouchUpInside];
        
        [_headerView addSubview:_sdcScrollView];
        [_headerView addSubview:_titleMoneyLabel];
        [_headerView addSubview:_countView];
//        [_headerView addSubview:joinBuyCarBtn];
        
        [_headerView.layer addSublayer:({
            CALayer *layer = [CALayer layer];
            layer.backgroundColor = getColor(@"f1f2f6").CGColor;
            layer.frame = CGRectMake(0, _headerView.frame.size.height-5, SCREEN_WIDTH, 5);
            layer;
        })];
        
    }
    return _headerView;
}

- (UIView *)footerView{
    if (!_footerView) {
        _footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.01)];
    }
    return _footerView;
}

- (UIView *)funcView{
    if (!_funcView) {
        _funcView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 64 - 44, SCREEN_WIDTH, 44)];
        _funcView.backgroundColor = [UIColor whiteColor];

        [_funcView addSubview:({
            UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH/2.-.5, 44)];
            btn.backgroundColor = getColor(@"f26822");
            [btn setTitle:@"加入购物车" forState:UIControlStateNormal];
            btn.titleLabel.font = DEF_FontSize_18;
            [btn addTarget:self action:@selector(joinBuyCarEvent) forControlEvents:UIControlEventTouchUpInside];
            btn;
        })];
        
        [_funcView addSubview:({
            UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2.+.5, 0, SCREEN_WIDTH/2., 44)];
            btn.backgroundColor = getColor(mainColor);
            [btn setTitle:@"立即购买" forState:UIControlStateNormal];
            btn.titleLabel.font = DEF_FontSize_18;
            [btn addTarget:self action:@selector(buyEvent) forControlEvents:UIControlEventTouchUpInside];
            btn;
        })];
    }
    return _funcView;
}

- (NSArray *)dataArray{
    if (!_dataArray) {
        _dataArray = @[];
    }
    return _dataArray;
}

- (NSString *)count{
    if (!_count) {
        _count = @"1";
    }
    return _count;
}

- (NSDictionary *)dataDictionary{
    if (!_dataDictionary) {
        _dataDictionary = @{};
    }
    return _dataDictionary;
}

- (NSMutableArray *)imgArray{
    if (!_imgArray) {
        _imgArray = @[].mutableCopy;
    }
    return _imgArray;
}

- (void)setGId:(NSString *)gId{
    _gId = gId;
    [self getData];
}

@end
